$(document).ready(function() {
    // 初始化加载全部歌单
    loadPlaylists('all');

    // 绑定分类点击事件
    $('.language-filter').on('click', function() {
        const language = $(this).data('language');
        loadPlaylists(language);
    });

    // 动态绑定歌单点击事件
    $(document).on('click', '.playlist-item', function() {
        const playlistId = $(this).data('playlist-id');
        if (playlistId) {
            window.location.href = `/dev/view/playlistDetails/playlistDetails.html?playlistId=${playlistId}`;
        }
    });
});

// 语言映射函数
function mapLanguage(lang) {
    const mapping = {
        'all': '全部',
        'chinese': '华语',
        'western': '欧美',
        'japanese': '日语',
        'korean': '韩语'
    };
    return mapping[lang] || '全部';
}

// 加载歌单数据
function loadPlaylists(lang) {
    $('.playlist-container').addClass('loading');
    $('.language-filter').removeClass('active');
    $(`[data-language="${lang}"]`).addClass('active');

    $.ajax({
        url: '/dev/playlist',
        method: 'GET',
        data: { languageType: mapLanguage(lang) },
        success: function(response) {
            if (response.code === '200') {
                renderPlaylists(response.data);
            }
        },
        error: function(xhr) {
            console.error('请求失败:', xhr.statusText);
        },
        complete: function() {
            $('.playlist-container').removeClass('loading');
        }
    });
}

// 渲染歌单（适配 imageUrl 字段）
function renderPlaylists(playlists) {
    const container = $('.playlist-container').empty();

    playlists.forEach(playlist => {
        // 处理图片路径（根据 imageUrl 字段）
        const imageUrl = playlist.imageUrl
            ? `/dev/img/${playlist.imageUrl}`
            : '/dev/img/default_cover.jpg';

        // 创建带数据属性的 DOM 元素
        const item = $(`
            <div class="col-sm-6 col-md-4 playlist-item" data-playlist-id="${playlist.id}">
                <div class="thumbnail">
                    <div class="playlist-cover" 
                         style="background-image: url('${imageUrl}')"
                         onerror="this.style.backgroundImage='url(/dev/img/default_cover.jpg)'">
                        <div class="play-count">播放：${playlist.playCount || 0}</div>
                    </div>
                    <div class="playlist-info">
                        <h4 class="playlist-title">${playlist.title || '未命名歌单'}</h4>
                        <p class="playlist-author">创建者：${playlist.creator || '未知用户'}</p>
                        <div class="stats">
                            <span class="favorite">♥ ${playlist.favoriteCount || 0}</span>
                            <span class="share">↗ ${playlist.shareCount || 0}</span>
                        </div>
                    </div>
                </div>
            </div>
        `);

        container.append(item);
    });
}